﻿/*globals phantom, console, require*/

(function () {
    'use strict';

    var page = require('webpage').create(),
        currentWait = 0,
        maximumWait = 1000,
        waitIncrement = 100;

    function releaseAndExit(exitCode, logMessage) {
        if (logMessage) {
            console.log(logMessage);
        }

        page.release();
        phantom.exit(exitCode);
    }

    function sandScriptReady() {
        return window.sandScript !== undefined;
    }

    function sandScriptReflect() {
        return window.sandScript.reflector.reflectAll();
    }

    function handleReflection() {
        var reflection;

        if (currentWait <= maximumWait) {
            if (page.evaluate(sandScriptReady)) {
                reflection = page.evaluate(sandScriptReflect);

                console.log('#_#Begin#_#');
                console.log(JSON.stringify(reflection));
                console.log('#_#End#_#');

                releaseAndExit(0);
            } else {
                currentWait += waitIncrement;
                setTimeout(handleReflection, waitIncrement);
            }
        } else {
            releaseAndExit(2, 'Timed out waiting for page to become ready.');
        }
    }

    function pageOpen(status) {
        if (status !== 'success') {
            releaseAndExit(1, 'Unable to open page.');
        } else {
            handleReflection();
        }
    }

    page.open(phantom.args[0], pageOpen);
}());
